package com.free4inno.knowledgems.utils;
import com.alibaba.fastjson.JSONObject;
import com.free4inno.knowledgems.dao.AttachmentDAO;
import com.free4inno.knowledgems.dao.CommentDAO;
import com.free4inno.knowledgems.domain.Attachment;
import com.free4inno.knowledgems.domain.Comment;
import com.free4inno.knowledgems.domain.Resource;
import com.free4inno.knowledgems.domain.ResourceES;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;
@Slf4j
@Component
public class WriteEsResourceHttpUtils {

    @Autowired
    private CommentDAO commentDao;

    @Autowired
    private AttachmentDAO attachmentDao;

    @Value("${spring.data.elasticsearch.cluster-nodes}")
    private String esNodes;

    @Value("${attatchment.download.url}")
    private String downloadUrl;

    @Value("${es.index.resource.name}")
    private String indexName;

    public ResourceES writeResourceToESHTTP(Resource resource, ResourceES resourceES) {
        //目前增加和修改资源都是用的这个方法
        String esHost = esNodes.substring(0, esNodes.indexOf(":"));
        String url = "http://" + esHost + ":9200/" + indexName + "/resource/" + resource.getId().toString();
        // set body json
        Map<String, Object> resource_es = new HashMap<>();
        resource_es.put("id", resource.getId());
        resource_es.put("crop_id", resource.getCropId());
        resource_es.put("user_id", resource.getUserId());
        resource_es.put("create_time", resource.getCreateTime());
        resource_es.put("edit_time", resource.getEditTime());
        resource_es.put("title", resource.getTitle());
        resource_es.put("text", resource.getText());
        resource_es.put("superior", resource.getSuperior());
        resource_es.put("recognition", resource.getRecognition());
        resource_es.put("opposition", resource.getOpposition());
        resource_es.put("pageview", resource.getPageview());
        resource_es.put("collection", resource.getCollection());
        resource_es.put("group_id", resource.getGroupId());
        resource_es.put("label_id", resource.getLabelId());
        resource_es.put("permissionId", resource.getPermissionId().toString());

        //进行附件解析
        List<Object> attach_list = new ArrayList<>();
        List<Attachment> attachmentList = attachmentDao.findAllByResourceId(resource.getId());
        if (attachmentList.size() != 0) {
            log.info(this.getClass().getName() + "----in----" + "取资源附件用于嵌套文档更新" + "----");
            //使用Tika进行附件解析
            attachmentList.forEach(attachment -> {
                //只解析未解析过的附件
                //if((attachment.getStatus().toString()!="SUCCESS")&&(attachment.getStatus().toString()!="success")) {
                    String text = TikaUtils.parseFile(downloadUrl + attachment.getUrl()); //暂时用这种方法实现一下
                    attachment.setOverTime(new Timestamp(new Date().getTime()));
                    // set body json
                    Map<String, Object> single_attach = new HashMap<>();
                    single_attach.put("resourceId", resource.getId());
                    single_attach.put("attachmentId", "attach_" + resource.getId() + "_" + attachment.getId());
                    single_attach.put("createTime", attachment.getCreateTime());
                    single_attach.put("name", attachment.getName());
                    single_attach.put("url", attachment.getUrl());
                    single_attach.put("attach_text", text);
                    if (text.equals("Error parsing file") || text.equals("Error reading file")) {
                        single_attach.put("status", text);
                        attachment.setStatus(Attachment.AttachmentEnum.FAILED);
                    }
                    else if (text.equals("Unsupported File Type")) {
                        single_attach.put("status", text);
                        attachment.setStatus(Attachment.AttachmentEnum.UNSUPPORTED);
                    }
                    else {
                        single_attach.put("status", "SUCCESS");
                        attachment.setStatus(Attachment.AttachmentEnum.SUCCESS);
                    }
                    attachmentDao.saveAndFlush(attachment);
                    attach_list.add(single_attach);
                //}
            });
        }
        resource_es.put("attachment", attach_list);

        //进行评论解析
        List<Object> comment_list = new ArrayList<>();
        List<Comment> commentList = commentDao.findByResourceId(resource.getId());
        commentList.forEach(comment -> {
            Map<String, Object> single_comment = new HashMap<>();
            single_comment.put("resourceId", comment.getResourceId());
            single_comment.put("user_id", comment.getUserId());
            single_comment.put("comment", comment.getContent());
            single_comment.put("time", comment.getTime());
            single_comment.put("userName", comment.getUserName());
            single_comment.put("picName", comment.getPicName());
            comment_list.add(single_comment);
        });
        resource_es.put("comment", comment_list);

        JSONObject json = new JSONObject(resource_es);
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        // http request

        RequestBody body = RequestBody.create(JSON, json.toString());
        Request request = new Request.Builder().url(url).put(body).build();
        OkHttpClient client = new OkHttpClient();
        try {
            Response response = client.newCall(request).execute();
            if (response.code() == 201) {
                log.info(this.getClass().getName() + "----out----" + "新建ES文档成功" + "----");
            } else if (response.code() == 200) {
                log.info(this.getClass().getName() + "----out----" + "更新ES文档成功" + "----");
            } else {
                log.info(this.getClass().getName() + "----out----" + "更新ES文档失败" + "----");
            }
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.info(this.getClass().getName() + "----out----" + "更新ES文档异常" + "----");
        }


        log.info(this.getClass().getName() + "----out----" + "返回写入后的resourceES" + "----");
        return resourceES;
    }
}
